import socket
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO)

# 配置 UDP 套接字
broadcast_host = '0.0.0.0'  # 监听所有接口
broadcast_port = 8766  # 与服务器配置的广播端口一致

def start_udp_listener():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    udp_socket.bind((broadcast_host, broadcast_port))
    logging.info(f"UDP监听器启动: {broadcast_host}:{broadcast_port}")

    while True:
        data, addr = udp_socket.recvfrom(1024)  # 缓冲区大小为1024字节
        message = data.decode('utf-8')
        logging.info(f"收到UDP广播消息: {message} from {addr}")

if __name__ == "__main__":
    start_udp_listener()
